//
// AWS Manager - A free AWS console application demonstrating advanced concepts
// Copyright (C) 2008-2010 Sean O'Dell. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
/*
 * EC2LaunchInstance.java
 *
 * Created on Jul 13, 2008, 7:39:25 PM
 */
package awsmanager;

import com.awsmanager.common.EC2Image;
import com.awsmanager.utils.ProcessText;
import com.sun.data.provider.RowKey;
import com.sun.rave.web.ui.appbase.AbstractPageBean;
import com.sun.webui.jsf.component.AddRemove;
import com.sun.webui.jsf.component.DropDown;
import com.sun.webui.jsf.component.PageAlert;
import com.sun.webui.jsf.component.TabSet;
import com.sun.webui.jsf.component.TextField;
import com.sun.webui.jsf.component.Upload;
import com.sun.webui.jsf.model.Option;
import com.sun.webui.jsf.model.SingleSelectOptionsList;
import com.sun.webui.jsf.model.UploadedFile;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.FacesException;
import javax.faces.component.html.HtmlInputTextarea;
import javax.faces.event.ValueChangeEvent;

/**
 * <p>Page bean that corresponds to a similarly named JSP page.  This
 * class contains component definitions (and initialization code) for
 * all components that you have defined on this page, as well as
 * lifecycle methods and event handlers where you may add behavior
 * to respond to incoming events.</p>
 *
 * @author Sean ODell
 */
public class EC2LaunchInstance extends AbstractPageBean {
    // <editor-fold defaultstate="collapsed" desc="Managed Component Definition">

    /**
     * <p>Automatically managed component initialization.  <strong>WARNING:</strong>
     * This method is automatically generated, so any user-specified code inserted
     * here is subject to being replaced.</p>
     */
    private void _init() throws Exception {
        ddl_InstanceTypeDefaultOptions.setOptions(new com.sun.webui.jsf.model.Option[]{new com.sun.webui.jsf.model.Option("m1.small", "m1.small"), new com.sun.webui.jsf.model.Option("m1.large", "m1.large"), new com.sun.webui.jsf.model.Option("m1.xlarge", "m1.xlarge"), new com.sun.webui.jsf.model.Option("c1.medium", "c1.medium"), new com.sun.webui.jsf.model.Option("c1.large", "c1.large")});
    }
    private SingleSelectOptionsList ddl_InstanceTypeDefaultOptions = new SingleSelectOptionsList();

    public SingleSelectOptionsList getDdl_InstanceTypeDefaultOptions() {
        return ddl_InstanceTypeDefaultOptions;
    }

    public void setDdl_InstanceTypeDefaultOptions(SingleSelectOptionsList ssol) {
        this.ddl_InstanceTypeDefaultOptions = ssol;
    }
    private HtmlInputTextarea ta_AMIsSelected = new HtmlInputTextarea();

    public HtmlInputTextarea getTa_AMIsSelected() {
        return ta_AMIsSelected;
    }

    public void setTa_AMIsSelected(HtmlInputTextarea hit) {
        this.ta_AMIsSelected = hit;
    }
    private DropDown ddl_InstanceType = new DropDown();

    public DropDown getDdl_InstanceType() {
        return ddl_InstanceType;
    }

    public void setDdl_InstanceType(DropDown dd) {
        this.ddl_InstanceType = dd;
    }
    private TextField tf_InstanceCount = new TextField();

    public TextField getTf_InstanceCount() {
        return tf_InstanceCount;
    }

    public void setTf_InstanceCount(TextField tf) {
        this.tf_InstanceCount = tf;
    }
    private DropDown ddl_AvailabilityZone = new DropDown();

    public DropDown getDdl_AvailabilityZone() {
        return ddl_AvailabilityZone;
    }

    public void setDdl_AvailabilityZone(DropDown dd) {
        this.ddl_AvailabilityZone = dd;
    }
    private Upload fu_UserDataFile = new Upload();

    public Upload getFu_UserDataFile() {
        return fu_UserDataFile;
    }

    public void setFu_UserDataFile(Upload u) {
        this.fu_UserDataFile = u;
    }
    private DropDown ddl_KeyPairs = new DropDown();

    public DropDown getDdl_KeyPairs() {
        return ddl_KeyPairs;
    }

    public void setDdl_KeyPairs(DropDown dd) {
        this.ddl_KeyPairs = dd;
    }
    private AddRemove ari_SecurityGroups = new AddRemove();

    public AddRemove getAri_SecurityGroups() {
        return ari_SecurityGroups;
    }

    public void setAri_SecurityGroups(AddRemove ar) {
        this.ari_SecurityGroups = ar;
    }
    private String zone = getSessionBean1().getEc2LaunchZoneDefault();
    private DropDown ddl_AKI = new DropDown();

    public DropDown getDdl_AKI() {
        return ddl_AKI;
    }

    public void setDdl_AKI(DropDown dd) {
        this.ddl_AKI = dd;
    }
    private DropDown ddl_ARI = new DropDown();

    public DropDown getDdl_ARI() {
        return ddl_ARI;
    }

    public void setDdl_ARI(DropDown dd) {
        this.ddl_ARI = dd;
    }

    // </editor-fold>
    /**
     * <p>Construct a new Page bean instance.</p>
     */
    public EC2LaunchInstance() {
    }

    /**
     * <p>Callback method that is called whenever a page is navigated to,
     * either directly via a URL, or indirectly via page navigation.
     * Customize this method to acquire resources that will be needed
     * for event handlers and lifecycle methods, whether or not this
     * page is performing post back processing.</p>
     * 
     * <p>Note that, if the current request is a postback, the property
     * values of the components do <strong>not</strong> represent any
     * values submitted with this request.  Instead, they represent the
     * property values that were saved for this view when it was rendered.</p>
     */
    @Override
    public void init() {
        // Perform initializations inherited from our superclass
        super.init();
        // Perform application initialization that must complete
        // *before* managed components are initialized
        // TODO - add your own initialiation code here

        // <editor-fold defaultstate="collapsed" desc="Managed Component Initialization">
        // Initialize automatically managed components
        // *Note* - this logic should NOT be modified
        try {
            _init();
        } catch (Exception e) {
            log("EC2RunInstance Initialization Failure", e);
            throw e instanceof FacesException ? (FacesException) e : new FacesException(e);
        }

    // </editor-fold>
    // Perform application initialization that must complete
    // *after* managed components are initialized
    // TODO - add your own initialization code here
    }

    /**
     * <p>Callback method that is called after the component tree has been
     * restored, but before any event processing takes place.  This method
     * will <strong>only</strong> be called on a postback request that
     * is processing a form submit.  Customize this method to allocate
     * resources that will be required in your event handlers.</p>
     */
    @Override
    public void preprocess() {
    }

    /**
     * <p>Callback method that is called just before rendering takes place.
     * This method will <strong>only</strong> be called for the page that
     * will actually be rendered (and not, for example, on a page that
     * handled a postback and then navigated to a different page).  Customize
     * this method to allocate resources that will be required for rendering
     * this page.</p>
     */
    @Override
    public void prerender() {
        String strlaunchInstanceList = new String();
        Map launchInstanceInfo = new HashMap(getSessionBean1().getLaunchInstInfo());
        ArrayList launchInstanceList = new ArrayList((ArrayList) launchInstanceInfo.get("instRowKeys"));
        for (int i = 0; i < launchInstanceList.size(); i++) {
            if (i > 0) {
                strlaunchInstanceList = strlaunchInstanceList + "\n";
            }
            EC2Image ec2Image = getSessionBean1().getEC2ImageDataProvider().getImage((RowKey) launchInstanceList.get(i));
            strlaunchInstanceList = strlaunchInstanceList + String.format("%-14s ", ec2Image.getimageId().toString());
        }
        ta_AMIsSelected.setValue(strlaunchInstanceList);
        ta_AMIsSelected.setReadonly(true);

        String launchZoneDefault = getSessionBean1().getEc2LaunchZoneDefault();

        if (launchZoneDefault == null) {
            Option[] zoneOptions = getSessionBean1().getEc2AvailabilityZoneOptions();
            launchZoneDefault = (String) zoneOptions[0].getValue();
            Map zonesToRegion = getSessionBean1().getEc2Connection().getEc2ZoneToRegion();
            String zoneRegion = (String) zonesToRegion.get(launchZoneDefault);

            Option[] keyPairsRegion = getSessionBean1().getEc2KeyPairDataProvider().getKeyPairNamesOptions(zoneRegion);
            Option[] securityGroupsRegion = getSessionBean1().getEc2SecurityGroupDataProvider().getSecurityGroupsOptions(zoneRegion);
            getSessionBean1().setEc2LaunchZoneDefault(launchZoneDefault);
            getSessionBean1().setKeyPairNamesRegionOptions(keyPairsRegion);
            getSessionBean1().setSecurityGroupsRegionOptions(securityGroupsRegion);
        }
    }

    /**
     * <p>Callback method that is called after rendering is completed for
     * this request, if <code>init()</code> was called (regardless of whether
     * or not this was the page that was actually rendered).  Customize this
     * method to release resources acquired in the <code>init()</code>,
     * <code>preprocess()</code>, or <code>prerender()</code> methods (or
     * acquired during execution of an event handler).</p>
     */
    @Override
    public void destroy() {
    }

    /**
     * <p>Return a reference to the scoped data bean.</p>
     *
     * @return reference to the scoped data bean
     */
    protected RequestBean1 getRequestBean1() {
        return (RequestBean1) getBean("RequestBean1");
    }

    /**
     * <p>Return a reference to the scoped data bean.</p>
     *
     * @return reference to the scoped data bean
     */
    protected SessionBean1 getSessionBean1() {
        return (SessionBean1) getBean("SessionBean1");
    }

    /**
     * <p>Return a reference to the scoped data bean.</p>
     *
     * @return reference to the scoped data bean
     */
    protected ApplicationBean1 getApplicationBean1() {
        return (ApplicationBean1) getBean("ApplicationBean1");
    }

    public String launchInstances_action() {

        Map launchInstanceInfo = new HashMap(getSessionBean1().getLaunchInstInfo());
        ArrayList launchInstanceList = new ArrayList((ArrayList) launchInstanceInfo.get("instRowKeys"));
        String uploadedFileName = new String();
        ArrayList securityGroupsList = null;
        String securityGroupsListStr = new String();

        int numInstances = 0;
        byte[] userdata = null;

        String type = (String) ddl_InstanceType.getValue();
        String keyPair = new String();
        String ec2AKI = new String();
        String ec2ARI = new String();

        String launchZone = (String) ddl_AvailabilityZone.getValue();
        String selectedItemsStr = ari_SecurityGroups.getSelectedValues();

        ProcessText processSecurityGroups = new ProcessText();
        try {
            securityGroupsList = processSecurityGroups.processText(
                    selectedItemsStr, ari_SecurityGroups.getSeparator());
        } catch (Exception ex) {
            Logger.getLogger(EC2LaunchInstance.class.getName()).log(Level.SEVERE, null, ex);
        }

        if (securityGroupsList != null) {
            for (int i = 0; i < securityGroupsList.size(); i++) {
                if (i != 0) {
                    securityGroupsListStr = securityGroupsListStr + ", ";
                }
                securityGroupsListStr = securityGroupsListStr + securityGroupsList.get(i);
            }
        }

        if (ddl_KeyPairs.getSelected() != null) {
            keyPair = ddl_KeyPairs.getSelected().toString();
        }

        if (ddl_AKI.getSelected() != null) {
            ec2AKI = ddl_AKI.getSelected().toString();
        }

        if (ddl_ARI.getSelected() != null) {
            ec2ARI = ddl_ARI.getSelected().toString();
        }

        try {
            numInstances = new Integer((String) tf_InstanceCount.getText());
        } catch (NumberFormatException e) {
            numInstances = 0;
        }

        if (numInstances <= 0) {
            info("Instance count must be an integer greater then 0.");
            return null;
        }

        UploadedFile uploadedFile = (UploadedFile) fu_UserDataFile.getUploadedFile();
        if (uploadedFile != null) {
            userdata = uploadedFile.getBytes();
            uploadedFileName = uploadedFile.getOriginalName();
            uploadedFile.dispose();
        }

        String detailMessage = new String();
        detailMessage = detailMessage + "Instance type                   : " + type + "\n";
        detailMessage = detailMessage + "Number of instances for each AMI: " + numInstances + "\n";
        detailMessage = detailMessage + "Security Groups                 : " + securityGroupsListStr + "\n";
        detailMessage = detailMessage + "Key Pair                        : " + keyPair + "\n";
        detailMessage = detailMessage + "Availability Zone:              : " + launchZone + "\n";
        detailMessage = detailMessage + "User Data File                  : " + uploadedFileName + "\n";
        detailMessage = detailMessage + "Kernel ID                       : " + ec2AKI + "\n";
        detailMessage = detailMessage + "RAM Disk ID                     : " + ec2ARI + "\n";
        detailMessage = detailMessage + "AMIs                            : ";

        for (int i = 0; i < launchInstanceList.size(); i++) {
            EC2Image ec2Image = getSessionBean1().getEC2ImageDataProvider().getImage((RowKey) launchInstanceList.get(i));
            if (i == 0) {
                detailMessage = detailMessage + String.format("%-14s\n", ec2Image.getimageId().toString());
            } else {
                detailMessage = detailMessage + String.format("%34s%-14s ", " ", ec2Image.getimageId().toString());
            }
        }

        launchInstanceInfo = new HashMap();

        launchInstanceInfo.put("instType", type);
        launchInstanceInfo.put("instCount", numInstances);
        launchInstanceInfo.put("instSecurityGroups", securityGroupsList);
        launchInstanceInfo.put("instKeyPair", keyPair);
        launchInstanceInfo.put("instZone", launchZone);
        launchInstanceInfo.put("userdata", userdata);
        launchInstanceInfo.put("instRowKeys", launchInstanceList);
        launchInstanceInfo.put("aki", ec2AKI);
        launchInstanceInfo.put("ari", ec2ARI);

        getSessionBean1().setLaunchInstInfo(launchInstanceInfo);

        PageAlert questionAlert = new PageAlert();
        questionAlert.setType("information");
        questionAlert.setTitle(" " + "Instances will be launched!");
        questionAlert.setDetail("Instances will be launched with the parameters listed below.");
        questionAlert.setSummary("Please press Continue to launch instances.\nUse the scroll bar, if available, to view all.");

        getSessionBean1().setPageAlertAWSActionType("launchInstances");
        getSessionBean1().setPageAlertDetailMessage(detailMessage);
        getSessionBean1().setUserPageAlert(questionAlert);
        getSessionBean1().setUserVisibleContinueBtn(true);
        getSessionBean1().setUserVisibleConnectBtn(false);
        getSessionBean1().setEc2LaunchZoneDefault(null);

        return "launchInst";
    }

    public String cancelBtn_action() {
        TabSet tabSet = getSessionBean1().getCurrentTabSet();
        if (tabSet != null) {
            tabSet.setSelected("EC2_Images");
            getSessionBean1().setCurrentTabSet(tabSet);
        }
        getSessionBean1().setEc2LaunchZoneDefault(null);
        return "cancel";
    }

    public void ta_AMIsSelected_processValueChange(ValueChangeEvent vce) {
    }

    public void ddl_AvailabilityZone_processValueChange(ValueChangeEvent event) {
        String launchZone = (String) ddl_AvailabilityZone.getValue();
        Map zonesToRegion = getSessionBean1().getEc2Connection().getEc2ZoneToRegion();
        String zoneRegion = (String) zonesToRegion.get(launchZone);

        Option[] keyPairsRegion = getSessionBean1().getEc2KeyPairDataProvider().getKeyPairNamesOptions(zoneRegion);
        Option[] securityGroupsRegion = getSessionBean1().getEc2SecurityGroupDataProvider().getSecurityGroupsOptions(zoneRegion);

        getSessionBean1().setKeyPairNamesRegionOptions(keyPairsRegion);
        getSessionBean1().setSecurityGroupsRegionOptions(securityGroupsRegion);
    }
}

